package repositories

import (
	"pass-tree/internal/logic/models"
)

func GetCategory() ([]models.Category, error) {
	ret, err := DB.Query("select * from category")
	if err != nil {
		return nil, err
	}
	var cs []models.Category
	for ret.Next() {
		var cat models.Category
		_ = ret.Scan(&cat.Id, &cat.Pid, &cat.Name, &cat.Desc)
		cs = append(cs, cat)
	}
	return cs, nil
}

func SaveCategory(category *models.Category) error {
	ret, err := DB.Exec("insert into category (pid,name,desc) values (?,?,?)", category.Pid, category.Name, category.Desc)
	if err != nil {
		return err
	}
	lastInsertId, err := ret.LastInsertId()
	if err != nil {
		return err
	}
	category.Id = int(lastInsertId)
	return nil
}

func UpdateCategory(category *models.Category) error {
	ret, err := DB.Exec("update category set name=?,desc=? where id=?", category.Name, category.Desc, category.Id)
	if err != nil {
		return err
	}
	lastInsertId, err := ret.LastInsertId()
	if err != nil {
		return err
	}
	category.Id = int(lastInsertId)
	return nil
}

func DeleteCategory(id int) error {
	ret, err := DB.Exec("delete from category where id=?", id)
	if err != nil {
		return err
	}
	_, err = ret.RowsAffected()
	if err != nil {
		return err
	}
	return nil
}
